import { SERVER_URL } from "@/constants/Path";
import { Podcast } from "@/constants/types";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Image,
  Keyboard,
  SafeAreaView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
const PodcastItem = ({ item }: { item: Podcast }) => {
  const router = useRouter();
  return (
    <TouchableOpacity
      onPress={() => {
        router.push({
          pathname: "/podcast",
          params: item,
        });
      }}
      style={{
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: "#eee",
      }}
    >
      <Image
        source={{ uri: item.artwork }}
        style={{
          width: 50,
          height: 50,
          borderRadius: 8,
          marginRight: 16,
        }}
      />
      <View
        style={{
          flex: 1,
        }}
      >
        <Text
          style={{
            fontSize: 16,
            marginBottom: 6,
          }}
        >
          {item.name}
        </Text>
        <Text
          style={{
            fontSize: 14,
            color: "#666",
          }}
        >
          {item.artist}
        </Text>
      </View>
    </TouchableOpacity>
  );
}
export default function PodcastsScreen() {
  const [search, setSearch] = useState("");
  const [isFocused, setIsFocused] = useState(false);
  const handleClear = () => {
    setSearch("");
    Keyboard.dismiss();
    setIsFocused(false);
  };

  const [podcastData, setPodcastData] = useState<Podcast[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const fetchPodcastData = async () => {
    setLoading(true);
    try {
      const response = await fetch(SERVER_URL + "/podcasts");
      const data = await response.json();
      setPodcastData(data.results);
    } catch (error) {
      console.log(error);
      Alert.alert('网络异常，请稍后重试')
    } finally {
      setLoading(false);
    }
  };

  const refreshData = async () => {
    setRefreshing(true);
    try {
      const response = await fetch(SERVER_URL + "/podcasts");
      const data = await response.json();
      setPodcastData(data.results);
    } catch (error) {
      console.log(error);
      await new Promise((resolve) => setTimeout(resolve, 1500));
      Alert.alert("网络异常，请稍后重试");
    } finally {
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchPodcastData();
  }, []);
  return (
    <SafeAreaView style={{ flex: 1 }}>
      {/* 标题 */}
      <Text style={{ textAlign: "center", fontSize: 18, margin: 10 }}>
        播客
      </Text>

      {/* 搜索框 */}
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          backgroundColor: "#e0e0e0",
          marginHorizontal: 16,
          marginTop: 20,
          borderRadius: 30,
          paddingVertical: 12,
          paddingHorizontal: 16,
          marginBottom: 16,
        }}
      >
        <Ionicons
          name="search"
          size={24}
          color="#333"
          style={{
            marginRight: 14,
          }}
        />
        <TextInput
          placeholder="搜索博客..."
          value={search}
          onChangeText={setSearch}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          style={{
            flex: 1,
            fontSize: 18,
            color: "#333",
            padding: 0,
          }}
          autoFocus={false}
          returnKeyType="search"
        />
        {isFocused && (
          <TouchableOpacity onPress={handleClear}>
            <Ionicons
              name="close"
              size={24}
              color="#333"
              style={{ marginLeft: 10 }}
            />
          </TouchableOpacity>
        )}
      </View>

      {/* 列表 */}
      {loading && <ActivityIndicator />}
      <FlatList
        data={podcastData.filter((item) => item)}
        renderItem={({ item }) => <PodcastItem item={item} />}
        keyExtractor={(item) => item.id}
        contentContainerStyle={{
          paddingHorizontal: 16,
        }}
        showsVerticalScrollIndicator={false}
        refreshing={refreshing}
        onRefresh={refreshData}
        ListEmptyComponent={
          <Text
            style={{
              textAlign: "center",
              fontSize: 18,
              marginBottom: 10,
              color: "#666",
            }}
          >
            暂无数据
          </Text>
        }
      />
    </SafeAreaView>
  );
}
